﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;
using zymarc;

namespace zymain
{
    public partial class FrmCxIso : Form
    {
        public int kjm;
        public string uid;
        private List<int> DbKayList;
        private List<string> DbJcList;
        private int fxsjm;
        private string  fxsjc;
        public FrmCxIso()
        {
            InitializeComponent();
        }

        private void qxbtn_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            base.Close();
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            string zdh = this.zdhTxt.Text.Trim();
            if (string.IsNullOrEmpty(zdh))
            {
                this.zdhTxt.Text = this.fxsjc.Trim() + DateTime.Now.ToString("yyyyMMddHHss");
                zdh = this.fxsjc.Trim() + DateTime.Now.ToString("yyyyMMddHHss");
            }
            if (this.fileTxt.Text.Equals(""))
            {
                MessageBox.Show("请选择ISO文件");
                this.openBtn_Click(sender, e);
            }
            else
            {
                int index = this.fileTxt.Text.LastIndexOf("\\");
                string filename = this.fileTxt.Text.Substring(index + 1);
                if (MessageBox.Show("确认要上装【" + filename + "】至选书库吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        FrmWait wait = new FrmWait();
                        wait.Show();
                        StreamReader reader = new StreamReader(this.fileTxt.Text, Encoding.Default);
                        string str; int m = 0, n = 0, i = 0;
                        while (reader.Peek() >= 0)
                        {
                            str = reader.ReadLine().ToString();
                            int yds = 0;
                            try
                            {
                                yds = Convert.ToInt32(this.ydsTxt.Text.Trim());
                            }catch{ }
                            if (str.Length > 0)
                            {
                                m += 1;
                                wait.label4.Text = "正在导入MARC数据 " + m.ToString();
                                Application.DoEvents();
                                Books b = GetBooks.SetBooks(str);
                                if (this.ydsCheck.Checked)
                                {
                                    if (b.Count > 0)
                                        yds = b.Count;
                                    else
                                    {
                                        MarcConvert convert = new MarcConvert();
                                        convert.ISOData = str;
                                        convert.SetISOtoMarc();
                                        convert.ReplaceSubfield("905", "a", 1, "GSL");
                                        convert.ReplaceSubfield("905", "f", 1, yds.ToString());
                                        convert.SetISOStr();
                                        str = convert.ISOData;
                                        b = GetBooks.SetBooks(str);
                                    }
                                }
                                if (b != null)
                                {
                                    b.Kjm = kjm;
                                    //Console.WriteLine(b.Marc);
                                    string title = this.ztRadio.Checked ? b.Ztitle : b.Title;
                                    if (StringUtil.GetStrLength(title) > 100)
                                        title = StringUtil.SubStrByte(title,0,100);
                                    object[,] value = new object[17, 2] {
                                        {"库键码",b.Kjm},
                                        {"题名",title},
                                        {"责任者",StringUtil.GetStrLength(b.Author)>50?StringUtil.SubStrByte(b.Author,0,50):b.Author},
                                        {"出版者",StringUtil.GetStrLength(b.Press)>50?StringUtil.SubStrByte(b.Press,0,50):b.Press},
                                        {"出版年",StringUtil.GetStrLength(b.Pdate)>20?StringUtil.SubStrByte(b.Pdate,0,20):b.Pdate},
                                        {"标准编码",b.Isbn},
                                        {"入库日期",b.Clrq},
                                        {"单价",StringUtil.GetStrLength(b.Ydj)>16?StringUtil.SubStrByte(b.Ydj,0,16):b.Ydj},
                                        {"订价",b.Sdj},
                                        {"分类",b.Ssh},
                                        {"订数",yds},
                                        {"操作员",this.uid},
                                        {"marc",b.Marc},
                                        {"征订号",zdh},
                                        {"开始时间",this.sTime.Text},
                                        {"结束时间",this.eTime.Text},
                                        {"图书来源",this.lyKay.Text}
                                    };
                                    _open.Reset();
                                    _open.AddFieldItems(value);
                                    _open.Insert("待采书库");
                                    n += 1;
                                }
                                else
                                    i++;
                            }
                        }
                        wait.Close();
                        if (m > 0)
                        {
                            object[,] value = new object[5, 2] {
                                        {"发行商键码",this.fxsjm},
                                        {"征订单号",zdh},
                                        {"开始时间",this.sTime.Text},
                                        {"库键码",this.kjm},
                                        {"馆键码",1}
                                    };
                            _open.Reset();
                            _open.AddFieldItems(value);
                            _open.Insert("选书征订单");
                            MessageBox.Show("文件【" + filename + "】[" + n + "]条成功导入");
                            DialogResult = DialogResult.OK;
                            base.Close();
                        }
                        else
                        {
                            MessageBox.Show("MARC文件有误!");
                            DialogResult = DialogResult.Cancel;
                            base.Close();
                        }
                    }
                }
                else
                {
                    DialogResult = DialogResult.Cancel;
                    base.Close();
                }
            }
            
        }
        public void AddDbList()
        {
            this.fxsKay.Items.Clear();
            this.DbKayList = new List<int>();
            this.DbKayList.Clear();
            this.DbJcList = new List<string>();
            this.DbJcList.Clear();
            using (DbOperHandler _open = new Common().Doh())
            {
                string sql = "select * from 发行商库";
                _open.Reset();
                _open.SqlCmd = sql;
                DataTable dt = _open.GetDataTable();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dRow in dt.Rows)
                    {
                        this.fxsKay.Items.Add(dRow["发行商"].ToString().Trim());
                        this.DbJcList.Add(dRow["发行商简称"].ToString());
                        this.DbKayList.Add(Convert.ToInt32(dRow["键码"].ToString()));
                    }
                }
                if (this.fxsKay.Items.Count > 0)
                {
                    this.fxsKay.SelectedIndex = 0;
                    this.fxsjc = this.DbJcList[0].ToString();
                    this.fxsjm = int.Parse(this.DbKayList[0].ToString());
                }
            }
        }
        private void skKay_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = this.fxsKay.SelectedIndex;
            this.fxsjc = this.DbJcList[selectedIndex].ToString();
            this.fxsjm = int.Parse(this.DbKayList[selectedIndex].ToString());
            this.zdhTxt.Text = this.fxsjc.Trim() + DateTime.Now.ToString("yyyyMMddHHss");
        }
        private void openBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "iso2709文件";
            dialog.Filter = "*.ISO|*.*";
            //dialog.ShowDialog();
            dialog.RestoreDirectory = true;//记录上次打开的目录
            dialog.Multiselect = false; //不允许选中多个文件
            dialog.ValidateNames = true;     //文件有效性验证ValidateNames，验证用户输入是否是一个有效的Windows文件名
            dialog.CheckFileExists = true;  //验证路径有效性
            dialog.CheckPathExists = true; //验证文件有效性
            string strName = this.fileTxt.Text.Trim();
            if (string.IsNullOrEmpty(strName))
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    strName = dialog.FileName;
                    this.fileTxt.Text = strName;
                    this.saveBtn.Enabled = true;
                }
            }
            else
            {
                if (MessageBox.Show("确认要清除当前文件，重新加载吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    strName = "";
                    this.fileTxt.Text = "";
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        strName = dialog.FileName;
                        this.fileTxt.Text = strName;
                        this.saveBtn.Enabled = true;
                    }
                }
            }
            if (strName == "")
            {
                MessageBox.Show("没有选择ISO文件！无法进行MARC数据上装");
                this.saveBtn.Enabled = false;
                return;
            }
        }

        private void FrmCxIso_Load(object sender, EventArgs e)
        {
            DateTime year = DateTime.Now.AddDays(180);
            DateChoser.AddTo(this.sTime);
            DateChoser.AddTo(this.eTime,year);
            this.lyKay.SelectedIndex = 0;
            this.AddDbList();
            string zdh = this.zdhTxt.Text.Trim();
            if (string.IsNullOrEmpty(zdh))
                this.zdhTxt.Text = this.fxsjc.Trim() + DateTime.Now.ToString("yyyyMMddHHss");
            //MessageBox.Show("" + this.kjm);
        }
    }
}
